package com.enjoy.xbase.qk.task;


import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;

import com.enjoy.xbase.qk.bean.ERR;
import com.enjoy.xbase.qk.impi.RequestBack;
import com.enjoy.xbase.qk.impi.RequestInfo;
import com.enjoy.xbase.qk.model.CommonModel;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;


/**
 * Created by cxb on 2018/6/25.
 */

public abstract class BaseTask implements Runnable {
    private CommonModel commonModel;
    private RequestBack back;
    private Handler handler;
    private RequestInfo requestInfo;

    public BaseTask(CommonModel commonModel, RequestBack back, RequestInfo requestInfo) {
        this.commonModel = commonModel;
        this.back = back;
        this.requestInfo = requestInfo;
        initHandler();
    }

    private void initHandler() {
        if (Looper.getMainLooper() != Looper.myLooper()) {//判断是否是主线程
            return;
        }
        handler = new DataHandler(this);
    }
    /**
     * @param code
     * @param msg
     */
    private void handelBack(int code, String msg) {
        if (code == 0) {//成功
            if (requestInfo.getDataProcessor() != null) {
                boolean handle = requestInfo.getDataProcessor().onReceive(commonModel.getUrl(), back.getData());
                if (handle) {
                    return;
                }
            }
            //tag未设置标签
            if (TextUtils.isEmpty(commonModel.getTag()) || requestInfo.isLastRemove(commonModel.getTag(), commonModel.getRequestTime())) {
                try {
                    back.onSuccess();
                } catch (Exception e) {
                    e.printStackTrace();
                    Writer writer = new StringWriter();
                    PrintWriter printWriter = new PrintWriter(writer);
                    e.printStackTrace(printWriter);
                    Throwable cause = e.getCause();
                    while (cause != null) {
                        cause.printStackTrace(printWriter);
                        cause = cause.getCause();
                    }
                    printWriter.close();
                    if (requestInfo.getDataProcessor() != null) {
                        requestInfo.getDataProcessor().onErr(ERR.ERR_DO);
                    }
                }
            }
        } else if (code == 1) {//请求失败
            if (ERR.ERR_DATA.msg.equals(msg) && !commonModel.isLogUp() && requestInfo.getDataProcessor() != null) {
                requestInfo.getDataProcessor().onErr(ERR.ERR_DATA);
            }
            //tag未设置标签
            if (TextUtils.isEmpty(commonModel.getTag()) || requestInfo.isLastRemove(commonModel.getTag(), commonModel.getRequestTime())) {
                back.onFailed(ERR.ERR_DATA);
            }
        } else if (code == 2) {
            back.onCancel();
        }
    }

    /**
     * 描述：设置结果数据
     *
     * @param content
     */
    public void setResultData(String content) {
        if (!requestInfo.isLast(commonModel.getTag(), commonModel.getRequestTime())) {
            return;
        }
        try {
            back.setRequestResult(content);
            if (handler != null) {
                Message msg = new Message();
                msg.what = 0;
                handler.sendMessage(msg);
            } else {
                handelBack(0, null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            setBackFail(ERR.ERR_DATA);
        }
    }

    public void setBackFail(ERR err) {
        if (handler != null) {
            Message hmsg = new Message();
            hmsg.what = 1;
            hmsg.obj = err.msg;
            handler.sendMessage(hmsg);
        } else {
            handelBack(1, err.msg);
        }
    }

    public void setBackCancel() {
        if (handler != null) {
            Message hmsg = new Message();
            hmsg.what = 2;
            hmsg.obj = "已取消";
            handler.sendMessage(hmsg);
        } else {
            handelBack(2, "已取消");
        }
    }

    static class DataHandler extends Handler {
        protected BaseTask task;

        public DataHandler(BaseTask task) {
            this.task = task;
        }

        @Override
        public void handleMessage(Message msg) {
            if (task != null) {
                task.handelBack(msg.what, (String) msg.obj);
            }
        }
    }
}